//
//  HMComposePictureView.swift
//  Weibo
//
//  Created by teacher on 2017/6/13.
//  Copyright © 2017年 teacher. All rights reserved.
//

import UIKit

//  撰写配图
class HMComposePictureView: UICollectionView {

    //  图片数据源
    lazy var images: [UIImage] = [UIImage]()
    //  执行点击加号的闭包
    var addPictureCallBack: (()->())?
    
    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        let flowLayout = UICollectionViewFlowLayout()
        //  item直接间距
        let itemMargin: CGFloat = 5
        //  计算item的大小
        let itemWidth = (ScreenWidth - 2 * HomeCellMargin - 2 * itemMargin) / 3
        flowLayout.itemSize = CGSize(width: itemWidth, height: itemWidth)
        //  设置最小item之间的间距
        flowLayout.minimumLineSpacing = itemMargin
        flowLayout.minimumInteritemSpacing = itemMargin
        super.init(frame: frame, collectionViewLayout: flowLayout)
        setupUI()
        
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI() {
        //  默认隐藏
        self.isHidden = true
        //  注册cell
        register(HMComposePictureViewCell.self, forCellWithReuseIdentifier: ComposePictureViewCellIdentifier)
        //  设置数据源代理
        dataSource = self
        //  设置代理
        delegate = self
    }
    //  显示选择的图片
    func showImage(image: UIImage) {
        if images.count == 9 {
            //  表示已经是9张图片了，不能再次添加
            return
        }
        
        //  添加图片显示配图
        self.isHidden = false
        images.append(image)
        //  重新加载数据
        reloadData()
    }

}

//  MARK:   --UICollectionViewDataSource
extension HMComposePictureView: UICollectionViewDataSource, UICollectionViewDelegate {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        //  如果是0或9张图片，图片数组的原始个数
        if images.count == 0 || images.count == 9 {
            return images.count
        } else {
            //  否则在原始图片数组个数的基础上加1 ，目的显示加号图片
            return images.count + 1
        }
        
        
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: ComposePictureViewCellIdentifier, for: indexPath) as! HMComposePictureViewCell
        //  如果item等于数组个数表示加号图片， 也就说做后一个cell
        if indexPath.item == images.count {
            //  表示加号图片
            cell.image = nil
        } else {
            //  设置图片
            cell.image = images[indexPath.item]
        }
        cell.indexPath = indexPath
        //  collectionview持有cell， cell持有闭包属性，闭包属性持有闭包，执行闭包，闭包不释放，那么self的引用计数是2，所有会产生循环引用
        //  解决办法 : 弱引用
        cell.deletePictureCallBack = { [unowned self] (index: Int) -> () in
            //  删除指定图片
            self.images.remove(at: index)
            //  重新加载数据
            self.reloadData()
            if self.images.count == 0 {
                //  隐藏配图
                self.isHidden = true
            }
            
        }
       
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        //  判断选择最后一个cell，表示加号
        if indexPath.item == images.count {
            print("我是加号")
            //  执行闭包完成回调
            addPictureCallBack?()
        }
    }
    
}

//  自定义撰写配图cell
class HMComposePictureViewCell: UICollectionViewCell {
    
    //  删除图片的闭包回调
    var deletePictureCallBack: ((Int)->())?
    
    //  MARK:   --懒加载控件
    fileprivate lazy var imageView: UIImageView = UIImageView()
    //  删除按钮
    fileprivate lazy var deleteButton: UIButton = {
        let button = UIButton()
        //  添加点击事件
        button.addTarget(self, action: #selector(deleteButtonAction), for: .touchUpInside)
        button.setImage(UIImage(named: "compose_photo_close"), for: .normal)
        return button
    }()
    
    //  设置indexPath
    var indexPath: IndexPath?
    
    //  显示图片
    var image: UIImage? {
        didSet {
            if image == nil {
                imageView.image = UIImage(named: "compose_pic_add")
                //  加号图片不显示删除按钮
                deleteButton.isHidden = true
            } else {
                imageView.image = image
                //  选择图片显示删除按钮
                deleteButton.isHidden = false
            }
            
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //  添加控件设置约束
    private func setupUI() {
        contentView.addSubview(imageView)
        contentView.addSubview(deleteButton)
        
        imageView.snp.makeConstraints { (make) in
            make.edges.equalTo(contentView)
        }
        
        deleteButton.snp.makeConstraints { (make) in
            make.top.equalTo(imageView)
            make.trailing.equalTo(imageView)
        }
    }
    
    //  MARK:   --删除按钮点击事件处理
    @objc private func deleteButtonAction() {
        //  删除图片，需要获取点击删除按钮对应cell的indexPath，获取item
        if let currentIndexPath = indexPath {
            //  获取对应的item
            let item = currentIndexPath.item
            //  执行闭包，完成数据回调
            deletePictureCallBack?(item)
        }
        
    }
}
